import { useState } from 'react';
import ConfirmDialog, { type ConfirmType } from '../components/ConfirmDialog';

interface ConfirmOptions {
  type?: ConfirmType;
  title?: string;
  message: string;
  itemName?: string;
  confirmText?: string;
  cancelText?: string;
  showWarning?: boolean;
}

interface ConfirmState {
  isOpen: boolean;
  options: ConfirmOptions;
  resolve?: (confirmed: boolean) => void;
  loading?: boolean;
}

export function useConfirm() {
  const [state, setState] = useState<ConfirmState>({
    isOpen: false,
    options: { message: '' },
    loading: false,
  });

  const confirm = (options: ConfirmOptions): Promise<boolean> => {
    return new Promise(resolve => {
      setState({
        isOpen: true,
        options: {
          type: 'question',
          title: '确认',
          showWarning: false,
          ...options,
        },
        resolve,
        loading: false,
      });
    });
  };

  const confirmDelete = (message: string, itemName?: string): Promise<boolean> => {
    return confirm({
      type: 'delete',
      title: '删除确认',
      message,
      itemName,
      confirmText: '确认删除',
      showWarning: true,
    });
  };

  const confirmWarning = (message: string, title = '警告'): Promise<boolean> => {
    return confirm({
      type: 'warning',
      title,
      message,
      showWarning: true,
    });
  };

  const confirmInfo = (message: string, title = '提示'): Promise<boolean> => {
    return confirm({
      type: 'info',
      title,
      message,
    });
  };

  const setLoading = (loading: boolean) => {
    setState(prev => ({ ...prev, loading }));
  };

  const handleConfirm = () => {
    state.resolve?.(true);
    setState(prev => ({ ...prev, isOpen: false, resolve: undefined }));
  };

  const handleCancel = () => {
    state.resolve?.(false);
    setState(prev => ({ ...prev, isOpen: false, resolve: undefined }));
  };

  const ConfirmComponent = () => (
    <ConfirmDialog
      isOpen={state.isOpen}
      type={state.options.type}
      title={state.options.title!}
      message={state.options.message}
      itemName={state.options.itemName}
      confirmText={state.options.confirmText}
      cancelText={state.options.cancelText}
      onConfirm={handleConfirm}
      onCancel={handleCancel}
      loading={state.loading}
      showWarning={state.options.showWarning}
    />
  );

  return {
    confirm,
    confirmDelete,
    confirmWarning,
    confirmInfo,
    setLoading,
    ConfirmComponent,
  };
}
